<template>
	<div class="orderList">
		<el-card shadow="hover">
			<div class="order-list mb15">
				<el-row>
					<el-col :span="24">
						<el-tabs v-model="orderState" @tab-change="onTabChange">
							<el-tab-pane
								v-for="(item, index) in ORDER_TABS"
								:name="item.value"
								:key="`order-tab-item-${index}`"
								:label="item.name"
								:value="item.value"
							></el-tab-pane>
						</el-tabs>
					</el-col>
				</el-row>
				<el-form ref="formDataRef" :inline="true" :model="formData" label-width="120px" class="demo-form-inline">
					<el-row>
						<el-col :span="8">
							<el-form-item prop="orderNumber" label="订单编号:" style="width: 100%">
								<el-input maxlength="200" v-model="formData.orderNumber" placeholder="订单编号" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item prop="customerInformation" label="客户信息" style="width: 100%">
								<el-input maxlength="200" @keyup.enter="searchFun()" v-model="formData.customerInformation" placeholder="模糊搜索" />
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item prop="tradeName" label="商品名称" style="width: 100%">
								<el-input maxlength="200" @keyup.enter="searchFun()" v-model="formData.tradeName" placeholder="商品名称" />
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item prop="paymentChannel" label="支付渠道" style="width: 100%">
								<el-select style="width: 100%" @change="searchFun()" v-model="formData.paymentChannel" placeholder="Select">
									<el-option v-for="item in PAYMENT_LIST" :key="item.value" :label="item.label" :value="item.value"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item prop="orderTime" label="下单时间" style="width: 100%">
								<el-date-picker
									value-format="YYYY-MM-DD"
									v-model="formData.orderTime"
									type="datetimerange"
									range-separator="To"
									start-placeholder="开始时间"
									end-placeholder="结束时间"
								></el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item prop="amountStart" label="订单金额" style="width: 100%">
								<div class="search_price_body">
									<div class="left">
										<el-input-number
											style="width: 100%"
											v-model="formData.amountStart"
											:step="1"
											:controls="false"
											:min="0"
											:max="MAX_LENGTH"
											controls-position="right"
										/>
									</div>
									<div class="content">至</div>
									<div class="right">
										<el-input-number
											style="width: 100%"
											v-model="formData.amountEnd"
											:step="1"
											:controls="false"
											:min="0"
											:max="MAX_LENGTH"
											controls-position="right"
										/>
									</div>
								</div>
							</el-form-item>
							<el-form-item prop="amountEnd"></el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item label="" style="width: 100%">
								<el-button type="primary" @click="searchFun()">搜索</el-button>
								<el-button @click="resetFrom">重置</el-button>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
			</div>
			<el-table v-loading="loading" :data="tableData" style="width: 100%">
				<el-table-column prop="checked" label width="80px">
					<template #default="scope">
						<el-checkbox v-model="scope.row.checked" label></el-checkbox>
					</template>
				</el-table-column>
				<el-table-column prop="orderNumber" label="序号" show-overflow-tooltip></el-table-column>
				<el-table-column width="170px" label="订单编号" show-overflow-tooltip>
					<template #default="scope">
						<el-link type="primary" @click="toDetail(scope.row)">{{ scope.row.orderSn }}</el-link>
					</template>
				</el-table-column>
				<el-table-column prop="createTime" width="150px" label="时间" show-overflow-tooltip></el-table-column>
				<el-table-column prop="memberUsername" width="150px" label="客户" show-overflow-tooltip></el-table-column>
				<el-table-column prop="totalAmount" label="订单合计" show-overflow-tooltip></el-table-column>
				<el-table-column prop="site" label="站点" show-overflow-tooltip></el-table-column>
				<el-table-column prop="couponId" width="60px" label="优惠券Id" show-overflow-tooltip></el-table-column>
				<el-table-column prop="couponAmount" width="150px" label="优惠券" show-overflow-tooltip></el-table-column>
				<!-- growth 0->德国；1->英国；2->美国 -->
				<el-table-column prop="growth" label="送达国家" show-overflow-tooltip></el-table-column>
				<!-- isPayed 是否支付；0未支付；1已支付 -->
				<el-table-column prop="isPayed" label="支付状态" show-overflow-tooltip>
					<template #default="scope">
						<span>{{ scope.row.isPayed ? '已支付' : '未支付' }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="payType" label="支付渠道" show-overflow-tooltip></el-table-column>
				<!-- status 订单状态：0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单 -->
				<!-- 确认收货状态：0->未确认；1->已确认 -->
				<el-table-column prop="status" label="订单状态" show-overflow-tooltip></el-table-column>
				<el-table-column prop="orderSource" label="订单来源" show-overflow-tooltip></el-table-column>
				<el-table-column
					prop="orderItemDetail"
					label="商品"
					:formatter="
						(row) => {
							return (row.orderItemDetail ? row.orderItemDetail.length : 0) + `件`;
						}
					"
					show-overflow-tooltip
				></el-table-column>
				<el-table-column label="操作" width="60px">
					<template #default="scope">
						<el-button text v-if="scope.row.isReturn !== REFUND_OCCURRED && scope.row.isPayed" type="primary" @click="beforeRefund(scope.row)"
							>退款</el-button
						>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				@size-change="onHandleSizeChange"
				@current-change="onHandleCurrentChange"
				class="mt15"
				:pager-count="5"
				:page-sizes="[10, 20, 30]"
				v-model:current-page="page.current"
				background
				v-model:page-size="page.pageSize"
				layout="total, sizes, prev, pager, next, jumper"
				:total="page.total"
			>
			</el-pagination>
		</el-card>
		<el-dialog destroy-on-close v-model="isShoworderDetail" width="80%" title="订单详情">
			<OrderDetail v-model:orderId="checkOrderId" v-model:isAfterSale="checkOrderIsAfterSale" @reloadList="searchFun()" />
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="isShoworderDetail = false">关闭</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>
<script setup name="OrderList">
import { ElMessage, ElMessageBox } from 'element-plus';
import OrderDetail from './OrderDetail.vue';
import orderPageState from '/@/utils/pageState/orderState';
import { useOrderApi } from '/@/api/order';
import { timeFormat } from '/@/utils/filters';
import dayjs from 'dayjs';
import couponState from '/@/utils/pageState/couponState';
import useCommonState from '/@/utils/pageState/commonState';
const { getSiteByPlatform } = useCommonState();

const {
	AFTER_SALE,
	getCountryText,
	getOrderSourceText,
	getPayTypeText,
	getReturnApplyStateText,
	getStatusText,
	ORDER_TABS,
	PAYMENT_LIST,
	REFUND_OCCURRED,
} = orderPageState();
const { getCurrencySymbolTextBySite, MAX_LENGTH } = couponState();
const { getOrderList, getOrderListByReturnApply, orderReturnApply } = useOrderApi();

let loading = ref(false);
let refundBtnLoading = ref(false);
let checkOrderId = ref(-1);
let checkOrderIsAfterSale = ref(false);
const isShoworderDetail = ref(false);
// 订单状态：0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单
let orderState = ref('null');
let tableData = ref([]);
let formData = ref({
	orderNumber: '',
	customerInformation: '',
	tradeName: '',
	paymentChannel: '',
	orderTime: [null, null],
	amountStart: 0,
	amountEnd: 0,
});
const page = ref({
	pageSize: 10,
	current: 1,
	total: 0,
});
const $route = useRoute();

init();

function init() {
	if ($route.query.id) {
		checkOrderId.value = Number($route.query.id);
		return;
	}
	beforeGetList();
}

function searchFun() {
	if (loading.value) {
		return;
	}
	page.value = {
		pageSize: page.value.pageSize,
		current: 1,
		total: page.value.total,
	};
	beforeGetList();
}

function beforeGetList() {
	if (orderState.value === AFTER_SALE) {
		getListByAfterSale();
		return;
	}
	getList();
}

async function getList() {
	if (loading.value) {
		return;
	}
	loading.value = true;
	try {
		let params = {
			current: page.value.current,
			pageSize: page.value.pageSize,
			memberId: null,
			status: orderState.value,
			deleteStatus: 0, // 删除状态：0->未删除；1->已删除；默认0
			payType: formData.value.paymentChannel ? formData.value.paymentChannel : null,
			orderSn: formData.value.orderNumber ? formData.value.orderNumber : null,
			strTime: formData.value.orderTime
				? formData.value.orderTime[0] === null
					? null
					: dayjs(formData.value.orderTime[0]).format('YYYY-MM-DD[T]HH:mm:ss[Z]')
				: null,
			endTime: formData.value.orderTime
				? formData.value.orderTime[1] === null
					? null
					: dayjs(formData.value.orderTime[1]).format('YYYY-MM-DD[T]HH:mm:ss[Z]')
				: null,
			minAmount: formData.value.amountStart ? formData.value.amountStart : null,
			maxAmount: formData.value.amountEnd ? formData.value.amountEnd : null,
			receiverName: formData.value.customerInformation ? formData.value.customerInformation : null,
			productName: formData.value.tradeName ? formData.value.tradeName : null,
		};
		if (orderState.value === 'null' || orderState.value === null) {
			params.type = 1;
		}
		let res = await getOrderList(params);
		if (res.code !== 200) {
			loading.value = false;
			// ElMessage({
			//     type: "error",
			//     message: res.data.msg,
			// });
			return;
		}
		loading.value = false;
		page.value = {
			pageSize: res.data.pageSize,
			current: res.data.current,
			total: res.data.total,
		};

		let tempList = [];

		tempList = res.data.data.map((item, index) => {
			return {
				id: item.id,
				checked: false,
				orderNumber: (res.data.current - 1) * 10 + index + 1,
				orderSn: item.orderSn,
				createTime: timeFormat(item.createTime),
				memberUsername: item.memberUsername,
				totalAmount: getCurrencySymbolTextBySite(item.sourceType) + item.payAmount,
				site: getSiteByPlatform(item.sourceType),
				couponAmount: item.promotionName,
				couponId: item.couponId,
				growth: getCountryText(item.growth),
				isPayed: item.isPayed,
				payType: getPayTypeText(item.payType),
				status: item.isReturn === REFUND_OCCURRED ? '发生退款' : getStatusText(item.status),
				orderSource: getOrderSourceText(item.sourceType),
				orderItemDetail: item.orderItemList,
				isAfterSale: orderState.value == AFTER_SALE ? true : false,
				isReturn: item.isReturn,
			};
		});

		tableData.value = tempList;
	} catch (error) {
		loading.value = false;
		ElMessage({
			type: 'error',
			message: '获取订单列表失败',
		});
	}
}

async function getListByAfterSale() {
	if (loading.value) {
		return;
	}
	loading.value = true;

	try {
		let params = {
			current: page.value.current,
			pageSize: page.value.pageSize,
			memberId: null,
			deleteStatus: 0, // 删除状态：0->未删除；1->已删除；默认0
			payType: formData.value.paymentChannel ? formData.value.paymentChannel : null,
			orderSn: formData.value.orderNumber ? formData.value.orderNumber : null,
			strTime: formData.value.orderTime
				? formData.value.orderTime[0] === null
					? null
					: dayjs(formData.value.orderTime[0]).format('YYYY-MM-DD[T]HH:mm:ss[Z]')
				: null,
			endTime: formData.value.orderTime
				? formData.value.orderTime[1] === null
					? null
					: dayjs(formData.value.orderTime[1]).format('YYYY-MM-DD[T]HH:mm:ss[Z]')
				: null,
			minAmount: formData.value.amountStart ? formData.value.amountStart : null,
			maxAmount: formData.value.amountEnd ? formData.value.amountEnd : null,
			receiverName: formData.value.customerInformation ? formData.value.customerInformation : null,
			productName: formData.value.tradeName ? formData.value.tradeName : null,
		};
		let res = await getOrderListByReturnApply(params);
		if (res.code !== 200) {
			loading.value = false;
			// ElMessage({
			//     type: "error",
			//     message: res.data.msg,
			// });
			return;
		}
		loading.value = false;
		page.value = {
			pageSize: res.data.pageSize,
			current: res.data.current,
			total: res.data.total,
		};

		let tempList = [];

		tempList = res.data.data.map((item, index) => {
			return {
				id: item.orderId,
				orderNumber: (res.data.data.current - 1) * 10 + index + 1,
				orderSn: item.orderSn,
				tradeName: item.productName,
				returnQuantity: item.productCount,
				applicationTime: timeFormat(item.createTime),
				customer: item.memberUsername,
				refundAmount: getCurrencySymbolTextBySite(item.sourceType) + item.returnAmount,
				payType: getPayTypeText(item.payType),
				applicationStatus: getReturnApplyStateText(item.status),
				refundSuccessTime: timeFormat(item.returnTime),
				site: getSiteByPlatform(item.sourceType),
				isAfterSale: true,
			};
		});

		tableData.value = tempList;
	} catch (error) {
		loading.value = false;
		ElMessage({
			type: 'error',
			message: '获取订单列表失败',
		});
	}
}
const formDataRef = ref();

function resetFrom() {
	formDataRef.value.resetFields();
}

// function tabClick(tab, event) {
// 	console.log('0--0---', event);
// 	console.log('0--111---', tab.name);
// 	console.log('0--0---', orderState.value);
// 	// 这里去触发搜索
// 	// beforeGetList();
// 	searchFun();
// }

const onTabChange = (name) => {
	orderState.value = Number(name);
	searchFun();
};

function toDetail(params) {
	checkOrderIsAfterSale.value = params.isAfterSale;
	checkOrderId.value = params.id;
	isShoworderDetail.value = true;
}

// 退款
async function refundFun(item, value) {
	if (refundBtnLoading.value) {
		return;
	}
	refundBtnLoading.value = true;
	let idLists = [];
	for (let index = 0; index < item.orderItemDetail.length; index++) {
		const element = item.orderItemDetail[index];
		idLists.push(element.id);
	}
	let params = {
		orderId: item.id,
		idLists,
		reason: value,
		description: '',
	};
	try {
		let res = await orderReturnApply(params);
		if (res.code !== 200) {
			refundBtnLoading.value = false;
			// ElMessage({
			//     type: "error",
			//     message: res.data.msg,
			// });
			return;
		}
		refundBtnLoading.value = false;
		ElMessage({
			type: 'success',
			message: '退款操作成功',
		});
		// emit("update:isAfterSale", true);
		getList();
	} catch (error) {
		refundBtnLoading.value = false;
		ElMessage({
			type: 'error',
			message: '退款操作失败',
		});
	}
}

// 退款弹窗
function beforeRefund(params) {
	ElMessageBox.prompt('请填写退款原因', '订单退款', {
		confirmButtonText: '提交',
		cancelButtonText: '取消',
		inputPattern: /^[\s\S]*.*[^\s][\s\S]*$/,
		inputErrorMessage: '退款原因不能为空',
	})
		.then(({ value }) => {
			refundFun(params, value);
		})
		.catch(() => {});
}

// 分页改变
const onHandleSizeChange = (val) => {
	page.pageSize = val;
	getList();
};
// 分页改变
const onHandleCurrentChange = (val) => {
	page.current = val;
	getList();
};
// 页面加载时
onMounted(() => {});
</script>
<style lang="scss" scoped>
.orderList {
	position: relative;
	.el-row {
		margin-bottom: 20px;
	}
	.line-box {
		display: flex;
		align-items: center;
		.input-name {
			width: 100px;
			text-align: right;
			padding-right: 10px;
		}
		.input-box {
			display: flex;
			flex: 1;
			overflow: hidden;
			align-items: center;
			.input-box-p {
				padding: 0 15px;
			}
			&.input-box-btns {
				width: 100%;
				padding-left: 35px;
			}
		}
	}
	.search_price_body {
		display: flex;
		width: 100%;
		.left,
		.right {
			width: 48%;
		}
		.content {
			flex: 1;
		}
	}
	.table-box {
	}
	.detail-box {
		width: 100%;
		height: 100%;
	}
}
</style>
